package com.itboye.ihomebank.activity.electric_meter;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;

import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.custom.datepicker.wheelview.OnWheelScrollListener;
import com.itboye.ihomebank.custom.datepicker.wheelview.WheelView;
import com.itboye.ihomebank.custom.datepicker.wheelview.adapter.NumericWheelAdapter;
import com.itboye.ihomebank.util.ByAlert;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by Administrator on 2018/8/24 0024.
 */

public class ActivityElectricBill extends BaseOtherActivity {

    View v_statusbar;
    ImageView close_icon;
    TextView add_shap_title_tv;

    ImageView img_other;//筛选日期

    ImageView line; //指针
    ViewPager pager;
    TextView historyRecordTv,rechargeRecordTv;
    List<Fragment> fragments;
    PagerAdapter mPagerAdapter;
    //line  的宽度 width / 2
    int width;
    private int beforePosition=0;//上一次的位置
    private int currIndex;//当前页
    private HistoryRechargeRecordFragment historyRecordFragment,rechargeRecordFragment;

    //未优化界面的选择pop
    private String yearSelect;
    private String startMonthSelect;
    private String endMonthSelect;

    //新的选择pop
    private WheelView year;
    private WheelView startMonth;
    private WheelView endMonth;

    PopupWindow datePop;
    TextView sureTv;
    Spinner spinnerYear,startMonthSpin,endMonthSpin;
    @Override
    protected int layout_id() {
        return R.layout.activity_electricbill;
    }

    @Override
    protected void onInitController() {

    }

    @Override
    protected void onInit() {

        setStatusBarHeight(v_statusbar);
        add_shap_title_tv.setText("账单");
        img_other.setVisibility(View.VISIBLE);
        img_other.setBackgroundResource(R.drawable.elec_date);

        currIndex=0;
        fragments=new ArrayList<>();


        historyRecordFragment=new HistoryRechargeRecordFragment();
        rechargeRecordFragment=new HistoryRechargeRecordFragment();
        fragments.add(historyRecordFragment); //添加历史账单
        fragments.add(rechargeRecordFragment); //添加充值记录
        mPagerAdapter=new PagerAdapter(getSupportFragmentManager(),fragments);
        pager.setAdapter(mPagerAdapter);

        historyRecordFragment.addType(1);
        rechargeRecordFragment.addType(2);
        WindowManager wm = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        width = wm.getDefaultDisplay().getWidth();

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width / 2, 10);
        line.setLayoutParams(params);
        line.setBackgroundResource(R.color.title_blue);

        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                if (position==currIndex){// 往右滑的时候position的值为当前的项的值
                    tranSlate(beforePosition,10,currIndex*width/2+width/2*positionOffset);
                    beforePosition = (int) (currIndex * width/2 + width/2 * positionOffset);

                }else if (position+1==currIndex){ // 往左滑的时候arg0的值为前一项的值
                    tranSlate(beforePosition,10,position*width/2+width/2*positionOffset);
                    beforePosition = (int) (position * width/2 + width/2 * positionOffset);
                }
            }

            @Override
            public void onPageSelected(int position) {
                currIndex=position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    protected void onReadIntent(Bundle bundle) {

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);

        switch (v.getId()){

            case R.id.close_icon://返回

                this.finish();
                break;
            case R.id.historyRecordTv://历史账单
                currIndex=0;
                pager.setCurrentItem(currIndex);
                break;
            case R.id.rechargeRecordTv://充值记录
                currIndex=1;
                pager.setCurrentItem(currIndex);
                break;

            case R.id.img_other: //筛选日期
                 showSelectPop();
//                 showPop();
                break;

            case R.id.sureTv: //确认 筛选的日期
                datePop.dismiss();
                if (Integer.parseInt(endMonthSelect)<Integer.parseInt(startMonthSelect)){
                    ByAlert.alert("时间选择错误");
                    return;
                }else {
                    //刷新数据
                   if (currIndex==0){
                       historyRecordFragment.refreshDada(yearSelect+startMonthSelect,yearSelect+endMonthSelect,1);
                   }else {
                       rechargeRecordFragment.refreshDada(yearSelect+startMonthSelect,yearSelect+endMonthSelect,2);
                   }
                }
                break;
        }
    }


    //viewpager adapter
    class PagerAdapter extends FragmentPagerAdapter{
        List<Fragment> fragments;

        public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments=fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    /**
     * 平移动画
     * @param beforePosition 之前的位置
     * @param durationMillis time
     * @param distance       需要滑动的距离
     */
    public void tranSlate(int beforePosition, long durationMillis,float distance) {
        Log.v("offest", "" + distance);
        Animation animation = new TranslateAnimation(beforePosition,
                distance, 0, 0);// 平移动画
        Log.v("currentoffest", "" + currIndex * distance);
        Log.v("currentItem", "" + distance);
        animation.setFillAfter(true);// 动画终止时停留在最后一帧，不然会回到没有执行前的状态
        animation.setDuration(durationMillis);// 动画持续时间0.2秒
        line.startAnimation(animation);// 是用ImageView来显示动画的
    }


    //显示
    private void showPop() {
        View contentView = LayoutInflater.from(ActivityElectricBill.this)
                .inflate(R.layout.pop_screendate, null);

         spinnerYear = (Spinner) contentView.findViewById(R.id.spinnerYear);
         startMonthSpin = (Spinner) contentView.findViewById(R.id.startMonthSpin);
         endMonthSpin = (Spinner) contentView.findViewById(R.id.endMonthSpin);
         sureTv= (TextView) contentView.findViewById(R.id.sureTv);
         sureTv.setOnClickListener(this);

        Calendar instance = Calendar.getInstance();
        int currentYear = instance.get(Calendar.YEAR);
        // 建立数据源
        final String[] mItems = new String[]{currentYear-2+"年",currentYear-1+"年",currentYear+"年",};
        final String[] monthArray = getResources().getStringArray(R.array.ele_month);

        ArrayAdapter<String> yearAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,mItems);
        spinnerYear.setAdapter(yearAdapter);
        ArrayAdapter<String> monthAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,monthArray);
        startMonthSpin.setAdapter(monthAdapter);
        endMonthSpin.setAdapter(monthAdapter);
//        private String yearSelect;
//        private String startMonthSelect;
//        private String endMonthSelect;

        startMonthSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                startMonthSelect=monthArray[position].substring(0,monthArray[position].length()-1);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        endMonthSpin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                endMonthSelect=monthArray[position].substring(0,monthArray[position].length()-1);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinnerYear.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                yearSelect=mItems[position].substring(0,mItems[position].length()-1);
                Log.d("=======ye",yearSelect);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        datePop=new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
        datePop.setAnimationStyle(R.style.popupwindow_anim_style);
        //passwordpop 可点击
        contentView.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        contentView.setFocusableInTouchMode(true); //comment by danielinbiti,设置view能够接听事件 标注2
        datePop.showAtLocation(contentView, Gravity.BOTTOM,0,0);

    }

    Calendar instance;
    //显示
    private void showSelectPop() {
        View contentView = LayoutInflater.from(ActivityElectricBill.this)
                .inflate(R.layout.pop_selectdate, null);

//         WheelView year;
//         WheelView startMonth;
//         WheelView endMonth;
        year= (WheelView) contentView.findViewById(R.id.year);
        startMonth= (WheelView) contentView.findViewById(R.id.startMonth);
        endMonth= (WheelView) contentView.findViewById(R.id.endMonth);
        sureTv= (TextView) contentView.findViewById(R.id.sureTv);
        sureTv.setOnClickListener(this);

        instance = Calendar.getInstance();
        int currentYear = instance.get(Calendar.YEAR);

        int curMonth = instance.get(Calendar.MONTH);

        NumericWheelAdapter numericWheelAdapter1 = new NumericWheelAdapter(
                this, currentYear-2, currentYear);
        numericWheelAdapter1.setTextSize(16);
        numericWheelAdapter1.setLabel("年");
        year.setViewAdapter(numericWheelAdapter1);
        year.setCurrentItem(2);
        year.setCyclic(false);// �Ƿ��ѭ������
        year.addScrollingListener(scrollListener);

        NumericWheelAdapter numericWheelAdapter2 = new NumericWheelAdapter(
                this, 1, 12, "%02d");
        numericWheelAdapter2.setLabel("月");
        numericWheelAdapter2.setTextSize(16);

        startMonth.setViewAdapter(numericWheelAdapter2);
        startMonth.addScrollingListener(scrollListener);
        startMonth.setCurrentItem(curMonth);
        startMonth.setCyclic(true);

        NumericWheelAdapter numericWheelAdapter3 = new NumericWheelAdapter(
                this, 1, 12, "%02d");
        numericWheelAdapter3.setLabel("月");
        numericWheelAdapter3.setTextSize(16);

        endMonth.setViewAdapter(numericWheelAdapter3);

        endMonth.addScrollingListener(scrollListener);
        endMonth.setCurrentItem(curMonth);
        endMonth.setCyclic(true);

        year.setVisibleItems(6);// ������ʾ����
        startMonth.setVisibleItems(6);
        endMonth.setVisibleItems(6);

        startMonthSelect=String.format("%02d", curMonth);
        endMonthSelect=String.format("%02d", curMonth);

        datePop=new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT,true);
//        datePop.setAnimationStyle(R.style.popupwindow_anim_style);
//        datePop.setContentView(contentView);
//        ColorDrawable dw = new ColorDrawable(0xb000000);
//        datePop.setBackgroundDrawable(dw);
        //passwordpop 可点击
        contentView.setFocusable(true);//comment by danielinbiti,设置view能够接听事件，标注1
        contentView.setFocusableInTouchMode(true); //comment by danielinbiti,设置view能够接听事件 标注2
        datePop.showAtLocation(contentView, Gravity.BOTTOM,0,0);

    }

    OnWheelScrollListener scrollListener = new OnWheelScrollListener() {
        @Override
        public void onScrollingStarted(WheelView wheel) {
            // if (isStart){
            //
            // }
        }
        @Override
        public void onScrollingFinished(WheelView wheel) {
            switch (wheel.getId()){
                case R.id.year:
                    int yearItem = wheel.getCurrentItem();
                    Calendar instance = Calendar.getInstance();
                    int currentYear = instance.get(Calendar.YEAR)-2+yearItem;
                    yearSelect=currentYear+"";
                    Log.d("=======ye",yearSelect);
                    break;
                case R.id.startMonth:
                    int mothItem = wheel.getCurrentItem()+1;
                    startMonthSelect=String.format("%02d", mothItem);
                    Log.d("=======ye",startMonthSelect);
                    break;
                case R.id.endMonth:
                    int mothItem1 = wheel.getCurrentItem()+1;
                    endMonthSelect=String.format("%02d", mothItem1);
                    Log.d("=======ye",endMonthSelect);
                    break;
            }
        }
    };


}
